/*
 * BSM6.0
 *
 * Copyright 2012-2013 (C) SINODATA CO., LTD. All Rights Reserved.
 */
package com.sinodata.bsm.cicp.util;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.util.Date;
import org.apache.commons.io.*;
import org.apache.log4j.Logger;

import com.sinodata.bsm.common.utils.DateUtil;

/**
 * <p>
 * Description: 
 * </p>
 *
 * @author tangli
 * @version 1.0

 * <p>
 * History: 
 *
 * Date                     Author         Version     Description
 * ---------------------------------------------------------------------------------
 * 2012-7-5 下午2:10:16          tangli         1.0         To create
 * </p>
 *
 * @since 
 * @see     
 */
public final class LocalReader {
    private static Logger cmdLogger = Logger.getLogger("cmdlog");
    private static final String DATE_FORMATE = "yyyy-MM-dd HH:mm:ss.S";
    private static Long last_run_time = 0L;

    /**
     * 执行本地命令，每次调用之间至少保持50毫秒的时间间隔
     * @param cmd
     * @return
     */
    protected static BufferedReader getLocalReader(String cmd) {
        Long interval = System.currentTimeMillis() - last_run_time;
        last_run_time = System.currentTimeMillis();
        if (interval < 50L) {
            try {
                Thread.sleep(50L - interval);
            } catch (InterruptedException e) {
            }
        }
        Process p = null;
        BufferedReader br = null;
        try {
            //执行命令
            p = Runtime.getRuntime().exec(cmd);
            br = new BufferedReader(new InputStreamReader(p.getInputStream(), "GBK"));
            String line = null;
            StringBuilder sb = new StringBuilder();
            while ((line = br.readLine()) != null) {
                sb.append(line + "\n");
            }
            BufferedReader buffReader = new BufferedReader(new StringReader(sb.toString()));
            String time = DateUtil.format(new Date(), DATE_FORMATE);
            cmdLogger.info("[SUCCEED]\t" + time + "\tlocalhost" + "\t" + cmd);
            return buffReader;
        } catch (Exception e) {
            String time = DateUtil.format(new Date(), DATE_FORMATE);
            cmdLogger.info("[FAILED]\t" + time + "\tlocalhost" + "\t" + cmd);
        } finally {
            IOUtils.closeQuietly(br);
            p.destroy();
        }
        return null;
    }

    /**
     * @param args
     * @throws IOException 
     */
    public static void main(String[] args) throws IOException {
    }

}
